#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <string.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <sys/socket.h>
#include <sys/wait.h>
#include<arpa/inet.h>
#define MYPORT    3490 		/* 监听端口 */
#define BACKLOG 10		/* listen的请求接收队列长度 */
void main()
{
	int sockfd, new_fd,numbytes; 		/* 监听端口，数据端口 */
  	char buf[100];
        struct sockaddr_in my_addr; 	/* 自身的地址信息 */
	struct sockaddr_in their_addr; 	/* 连接对方的地址信息 */
	int sin_size;
	if ((sockfd = socket(AF_INET, SOCK_STREAM, 0)) == -1) {
		perror("socket");
		exit(1);
	}

	my_addr.sin_family = AF_INET; 
	my_addr.sin_port = htons(MYPORT); 		/* 网络字节顺序 */
	my_addr.sin_addr.s_addr = INADDR_ANY; 	/* 自动填本机IP */
	bzero(&(my_addr.sin_zero), 8); 		/* 其余部分置0 */

	if(bind(sockfd, (struct sockaddr *)&my_addr, 
			  sizeof(struct sockaddr)) == -1) 
	{
		perror("bind");
		exit(1);
	}

	if (listen(sockfd, BACKLOG) == -1) {
		perror("listen");
		exit(1);
	}
	while(1) { 			/* 主循环 */
		sin_size = sizeof(struct sockaddr_in);
		new_fd = accept(sockfd, (struct sockaddr *)&their_addr, &sin_size);
		if  (new_fd == -1) {
			perror("accept");
			continue; 
		}
		printf("Got connection from %s\n",inet_ntoa(their_addr.sin_addr));
	 while(1)
       {
	   if ((numbytes=recv(new_fd,buf,sizeof(buf),0))==-1) 	
	   {
		perror("recv");
		//exit(1);
	   }
          if(strcmp(buf,"goodbye")==0)break;
           buf[numbytes] = '\0';
           printf("Received: %s\n",buf);
           printf("please input a word:\n");
           scanf("%s",&buf);
           if (send(new_fd, buf, sizeof(buf), 0) == -1) perror("send");
       }
                printf("当前客户已断开\n");break;
               close(new_fd); /* 无法生成子进程时有用 */
	//	while(waitpid(-1,NULL,WNOHANG) > 0); 	/*清除所有子进程 */
	}
}
